home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / socket.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  19.5 KB  |  562 lines

  1. # Wrapper module for _socket, providing some additional facilities
  2. # implemented in Python.
  3.  
  4. """\
  5. This module provides socket operations and some related functions.
  6. On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
  7. On other systems, it only supports IP. Functions specific for a
  8. socket are available as methods of the socket object.
  9.  
  10. Functions:
  11.  
  12. socket() -- create a new socket object
  13. socketpair() -- create a pair of new socket objects [*]
  14. fromfd() -- create a socket object from an open file descriptor [*]
  15. gethostname() -- return the current hostname
  16. gethostbyname() -- map a hostname to its IP number
  17. gethostbyaddr() -- map an IP number or hostname to DNS info
  18. getservbyname() -- map a service name and a protocol name to a port number
  19. getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
  20. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
  21. htons(), htonl() -- convert 16, 32 bit int from host to network byte order
  22. inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
  23. inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
  24. ssl() -- secure socket layer support (only available if configured)
  25. socket.getdefaulttimeout() -- get the default timeout value
  26. socket.setdefaulttimeout() -- set the default timeout value
  27. create_connection() -- connects to an address, with an optional timeout
  28.  
  29.  [*] not available on all platforms!
  30.  
  31. Special objects:
  32.  
  33. SocketType -- type object for socket objects
  34. error -- exception raised for I/O errors
  35. has_ipv6 -- boolean value indicating if IPv6 is supported
  36.  
  37. Integer constants:
  38.  
  39. AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
  40. SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
  41.  
  42. Many other constants may be defined; these may be used in calls to
  43. the setsockopt() and getsockopt() methods.
  44. """
  45.  
  46. import _socket
  47. from _socket import *
  48.  
  49. try:
  50.     import _ssl
  51. except ImportError:
  52.     # no SSL support
  53.     pass
  54. else:
  55.     def ssl(sock, keyfile=None, certfile=None):
  56.         # we do an internal import here because the ssl
  57.         # module imports the socket module
  58.         import ssl as _realssl
  59.         warnings.warn("socket.ssl() is deprecated.  Use ssl.wrap_socket() instead.",
  60.                       DeprecationWarning, stacklevel=2)
  61.         return _realssl.sslwrap_simple(sock, keyfile, certfile)
  62.  
  63.     # we need to import the same constants we used to...
  64.     from _ssl import SSLError as sslerror
  65.     from _ssl import \
  66.          RAND_add, \
  67.          RAND_egd, \
  68.          RAND_status, \
  69.          SSL_ERROR_ZERO_RETURN, \
  70.          SSL_ERROR_WANT_READ, \
  71.          SSL_ERROR_WANT_WRITE, \
  72.          SSL_ERROR_WANT_X509_LOOKUP, \
  73.          SSL_ERROR_SYSCALL, \
  74.          SSL_ERROR_SSL, \
  75.          SSL_ERROR_WANT_CONNECT, \
  76.          SSL_ERROR_EOF, \
  77.          SSL_ERROR_INVALID_ERROR_CODE
  78.  
  79. import os, sys, warnings
  80.  
  81. try:
  82.     from cStringIO import StringIO
  83. except ImportError:
  84.     from StringIO import StringIO
  85.  
  86. try:
  87.     import errno
  88. except ImportError:
  89.     errno = None
  90. EBADF = getattr(errno, 'EBADF', 9)
  91. EINTR = getattr(errno, 'EINTR', 4)
  92.  
  93. __all__ = ["getfqdn", "create_connection"]
  94. __all__.extend(os._get_exports_list(_socket))
  95.  
  96.  
  97. _realsocket = socket
  98.  
  99. # WSA error codes
  100. if sys.platform.lower().startswith("win"):
  101.     errorTab = {}
  102.     errorTab[10004] = "The operation was interrupted."
  103.     errorTab[10009] = "A bad file handle was passed."
  104.     errorTab[10013] = "Permission denied."
  105.     errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
  106.     errorTab[10022] = "An invalid operation was attempted."
  107.     errorTab[10035] = "The socket operation would block"
  108.     errorTab[10036] = "A blocking operation is already in progress."
  109.     errorTab[10048] = "The network address is in use."
  110.     errorTab[10054] = "The connection has been reset."
  111.     errorTab[10058] = "The network has been shut down."
  112.     errorTab[10060] = "The operation timed out."
  113.     errorTab[10061] = "Connection refused."
  114.     errorTab[10063] = "The name is too long."
  115.     errorTab[10064] = "The host is down."
  116.     errorTab[10065] = "The host is unreachable."
  117.     __all__.append("errorTab")
  118.  
  119.  
  120.  
  121. def getfqdn(name=''):
  122.     """Get fully qualified domain name from name.
  123.  
  124.     An empty argument is interpreted as meaning the local host.
  125.  
  126.     First the hostname returned by gethostbyaddr() is checked, then
  127.     possibly existing aliases. In case no FQDN is available, hostname
  128.     from gethostname() is returned.
  129.     """
  130.     name = name.strip()
  131.     if not name or name == '0.0.0.0':
  132.         name = gethostname()
  133.     try:
  134.         hostname, aliases, ipaddrs = gethostbyaddr(name)
  135.     except error:
  136.         pass
  137.     else:
  138.         aliases.insert(0, hostname)
  139.         for name in aliases:
  140.             if '.' in name:
  141.                 break
  142.         else:
  143.             name = hostname
  144.     return name
  145.  
  146.  
  147. _socketmethods = (
  148.     'bind', 'connect', 'connect_ex', 'fileno', 'listen',
  149.     'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
  150.     'sendall', 'setblocking',
  151.     'settimeout', 'gettimeout', 'shutdown')
  152.  
  153. if os.name == "nt":
  154.     _socketmethods = _socketmethods + ('ioctl',)
  155.  
  156. if sys.platform == "riscos":
  157.     _socketmethods = _socketmethods + ('sleeptaskw',)
  158.  
  159. # All the method names that must be delegated to either the real socket
  160. # object or the _closedsocket object.
  161. _delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into",
  162.                      "send", "sendto")
  163.  
  164. class _closedsocket(object):
  165.     __slots__ = []
  166.     def _dummy(*args):
  167.         raise error(EBADF, 'Bad file descriptor')
  168.     # All _delegate_methods must also be initialized here.
  169.     send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
  170.     __getattr__ = _dummy
  171.  
  172. # Wrapper around platform socket objects. This implements
  173. # a platform-independent dup() functionality. The
  174. # implementation currently relies on reference counting
  175. # to close the underlying socket object.
  176. class _socketobject(object):
  177.  
  178.     __doc__ = _realsocket.__doc__
  179.  
  180.     __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)
  181.  
  182.     def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
  183.         if _sock is None:
  184.             _sock = _realsocket(family, type, proto)
  185.         self._sock = _sock
  186.         for method in _delegate_methods:
  187.             setattr(self, method, getattr(_sock, method))
  188.  
  189.     def close(self):
  190.         self._sock = _closedsocket()
  191.         dummy = self._sock._dummy
  192.         for method in _delegate_methods:
  193.             setattr(self, method, dummy)
  194.     close.__doc__ = _realsocket.close.__doc__
  195.  
  196.     def accept(self):
  197.         sock, addr = self._sock.accept()
  198.         return _socketobject(_sock=sock), addr
  199.     accept.__doc__ = _realsocket.accept.__doc__
  200.  
  201.     def dup(self):
  202.         """dup() -> socket object
  203.  
  204.         Return a new socket object connected to the same system resource."""
  205.         return _socketobject(_sock=self._sock)
  206.  
  207.     def makefile(self, mode='r', bufsize=-1):
  208.         """makefile([mode[, bufsize]]) -> file object
  209.  
  210.         Return a regular file object corresponding to the socket.  The mode
  211.         and bufsize arguments are as for the built-in open() function."""
  212.         return _fileobject(self._sock, mode, bufsize)
  213.  
  214.     family = property(lambda self: self._sock.family, doc="the socket family")
  215.     type = property(lambda self: self._sock.type, doc="the socket type")
  216.     proto = property(lambda self: self._sock.proto, doc="the socket protocol")
  217.  
  218.     _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
  219.           "%s.__doc__ = _realsocket.%s.__doc__\n")
  220.     for _m in _socketmethods:
  221.         exec _s % (_m, _m, _m, _m)
  222.     del _m, _s
  223.  
  224. socket = SocketType = _socketobject
  225.  
  226. class _fileobject(object):
  227.     """Faux file object attached to a socket object."""
  228.  
  229.     default_bufsize = 8192
  230.     name = "<socket>"
  231.  
  232.     __slots__ = ["mode", "bufsize", "softspace",
  233.                  # "closed" is a property, see below
  234.                  "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", "_wbuf_len",
  235.                  "_close"]
  236.  
  237.     def __init__(self, sock, mode='rb', bufsize=-1, close=False):
  238.         self._sock = sock
  239.         self.mode = mode # Not actually used in this version
  240.         if bufsize < 0:
  241.             bufsize = self.default_bufsize
  242.         self.bufsize = bufsize
  243.         self.softspace = False
  244.         # _rbufsize is the suggested recv buffer size.  It is *strictly*
  245.         # obeyed within readline() for recv calls.  If it is larger than
  246.         # default_bufsize it will be used for recv calls within read().
  247.         if bufsize == 0:
  248.             self._rbufsize = 1
  249.         elif bufsize == 1:
  250.             self._rbufsize = self.default_bufsize
  251.         else:
  252.             self._rbufsize = bufsize
  253.         self._wbufsize = bufsize
  254.         # We use StringIO for the read buffer to avoid holding a list
  255.         # of variously sized string objects which have been known to
  256.         # fragment the heap due to how they are malloc()ed and often
  257.         # realloc()ed down much smaller than their original allocation.
  258.         self._rbuf = StringIO()
  259.         self._wbuf = [] # A list of strings
  260.         self._wbuf_len = 0
  261.         self._close = close
  262.  
  263.     def _getclosed(self):
  264.         return self._sock is None
  265.     closed = property(_getclosed, doc="True if the file is closed")
  266.  
  267.     def close(self):
  268.         try:
  269.             if self._sock:
  270.                 self.flush()
  271.         finally:
  272.             if self._close:
  273.                 self._sock.close()
  274.             self._sock = None
  275.  
  276.     def __del__(self):
  277.         try:
  278.             self.close()
  279.         except:
  280.             # close() may fail if __init__ didn't complete
  281.             pass
  282.  
  283.     def flush(self):
  284.         if self._wbuf:
  285.             data = "".join(self._wbuf)
  286.             self._wbuf = []
  287.             self._wbuf_len = 0
  288.             buffer_size = max(self._rbufsize, self.default_bufsize)
  289.             data_size = len(data)
  290.             write_offset = 0
  291.             try:
  292.                 while write_offset < data_size:
  293.                     with warnings.catch_warnings():
  294.                         if sys.py3kwarning:
  295.                             warnings.filterwarnings("ignore", ".*buffer",
  296.                                                     DeprecationWarning)
  297.                         self._sock.sendall(buffer(data, write_offset, buffer_size))
  298.                     write_offset += buffer_size
  299.             finally:
  300.                 if write_offset < data_size:
  301.                     remainder = data[write_offset:]
  302.                     del data  # explicit free
  303.                     self._wbuf.append(remainder)
  304.                     self._wbuf_len = len(remainder)
  305.  
  306.     def fileno(self):
  307.         return self._sock.fileno()
  308.  
  309.     def write(self, data):
  310.         data = str(data) # XXX Should really reject non-string non-buffers
  311.         if not data:
  312.             return
  313.         self._wbuf.append(data)
  314.         self._wbuf_len += len(data)
  315.         if (self._wbufsize == 0 or
  316.             self._wbufsize == 1 and '\n' in data or
  317.             self._wbuf_len >= self._wbufsize):
  318.             self.flush()
  319.  
  320.     def writelines(self, list):
  321.         # XXX We could do better here for very long lists
  322.         # XXX Should really reject non-string non-buffers
  323.         lines = filter(None, map(str, list))
  324.         self._wbuf_len += sum(map(len, lines))
  325.         self._wbuf.extend(lines)
  326.         if (self._wbufsize <= 1 or
  327.             self._wbuf_len >= self._wbufsize):
  328.             self.flush()
  329.  
  330.     def _get_wbuf_len(self):
  331.         return self._wbuf_len
  332.  
  333.     def read(self, size=-1):
  334.         # Use max, disallow tiny reads in a loop as they are very inefficient.
  335.         # We never leave read() with any leftover data from a new recv() call
  336.         # in our internal buffer.
  337.         rbufsize = max(self._rbufsize, self.default_bufsize)
  338.         # Our use of StringIO rather than lists of string objects returned by
  339.         # recv() minimizes memory usage and fragmentation that occurs when
  340.         # rbufsize is large compared to the typical return value of recv().
  341.         buf = self._rbuf
  342.         buf.seek(0, 2)  # seek end
  343.         if size < 0:
  344.             # Read until EOF
  345.             self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
  346.             while True:
  347.                 try:
  348.                     data = self._sock.recv(rbufsize)
  349.                 except error, e:
  350.                     if e.args[0] == EINTR:
  351.                         continue
  352.                     raise
  353.                 if not data:
  354.                     break
  355.                 buf.write(data)
  356.             return buf.getvalue()
  357.         else:
  358.             # Read until size bytes or EOF seen, whichever comes first
  359.             buf_len = buf.tell()
  360.             if buf_len >= size:
  361.                 # Already have size bytes in our buffer?  Extract and return.
  362.                 buf.seek(0)
  363.                 rv = buf.read(size)
  364.                 self._rbuf = StringIO()
  365.                 self._rbuf.write(buf.read())
  366.                 return rv
  367.  
  368.             self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
  369.             while True:
  370.                 left = size - buf_len
  371.                 # recv() will malloc the amount of memory given as its
  372.                 # parameter even though it often returns much less data
  373.                 # than that.  The returned data string is short lived
  374.                 # as we copy it into a StringIO and free it.  This avoids
  375.                 # fragmentation issues on many platforms.
  376.                 try:
  377.                     data = self._sock.recv(left)
  378.                 except error, e:
  379.                     if e.args[0] == EINTR:
  380.                         continue
  381.                     raise
  382.                 if not data:
  383.                     break
  384.                 n = len(data)
  385.                 if n == size and not buf_len:
  386.                     # Shortcut.  Avoid buffer data copies when:
  387.                     # - We have no data in our buffer.
  388.                     # AND
  389.                     # - Our call to recv returned exactly the
  390.                     #   number of bytes we were asked to read.
  391.                     return data
  392.                 if n == left:
  393.                     buf.write(data)
  394.                     del data  # explicit free
  395.                     break
  396.                 assert n <= left, "recv(%d) returned %d bytes" % (left, n)
  397.                 buf.write(data)
  398.                 buf_len += n
  399.                 del data  # explicit free
  400.                 #assert buf_len == buf.tell()
  401.             return buf.getvalue()
  402.  
  403.     def readline(self, size=-1):
  404.         buf = self._rbuf
  405.         buf.seek(0, 2)  # seek end
  406.         if buf.tell() > 0:
  407.             # check if we already have it in our buffer
  408.             buf.seek(0)
  409.             bline = buf.readline(size)
  410.             if bline.endswith('\n') or len(bline) == size:
  411.                 self._rbuf = StringIO()
  412.                 self._rbuf.write(buf.read())
  413.                 return bline
  414.             del bline
  415.         if size < 0:
  416.             # Read until \n or EOF, whichever comes first
  417.             if self._rbufsize <= 1:
  418.                 # Speed up unbuffered case
  419.                 buf.seek(0)
  420.                 buffers = [buf.read()]
  421.                 self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
  422.                 data = None
  423.                 recv = self._sock.recv
  424.                 while True:
  425.                     try:
  426.                         while data != "\n":
  427.                             data = recv(1)
  428.                             if not data:
  429.                                 break
  430.                             buffers.append(data)
  431.                     except error, e:
  432.                         # The try..except to catch EINTR was moved outside the
  433.                         # recv loop to avoid the per byte overhead.
  434.                         if e.args[0] == EINTR:
  435.                             continue
  436.                         raise
  437.                     break
  438.                 return "".join(buffers)
  439.  
  440.             buf.seek(0, 2)  # seek end
  441.             self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
  442.             while True:
  443.                 try:
  444.                     data = self._sock.recv(self._rbufsize)
  445.                 except error, e:
  446.                     if e.args[0] == EINTR:
  447.                         continue
  448.                     raise
  449.                 if not data:
  450.                     break
  451.                 nl = data.find('\n')
  452.                 if nl >= 0:
  453.                     nl += 1
  454.                     buf.write(data[:nl])
  455.                     self._rbuf.write(data[nl:])
  456.                     del data
  457.                     break
  458.                 buf.write(data)
  459.             return buf.getvalue()
  460.         else:
  461.             # Read until size bytes or \n or EOF seen, whichever comes first
  462.             buf.seek(0, 2)  # seek end
  463.             buf_len = buf.tell()
  464.             if buf_len >= size:
  465.                 buf.seek(0)
  466.                 rv = buf.read(size)
  467.                 self._rbuf = StringIO()
  468.                 self._rbuf.write(buf.read())
  469.                 return rv
  470.             self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
  471.             while True:
  472.                 try:
  473.                     data = self._sock.recv(self._rbufsize)
  474.                 except error, e:
  475.                     if e.args[0] == EINTR:
  476.                         continue
  477.                     raise
  478.                 if not data:
  479.                     break
  480.                 left = size - buf_len
  481.                 # did we just receive a newline?
  482.                 nl = data.find('\n', 0, left)
  483.                 if nl >= 0:
  484.                     nl += 1
  485.                     # save the excess data to _rbuf
  486.                     self._rbuf.write(data[nl:])
  487.                     if buf_len:
  488.                         buf.write(data[:nl])
  489.                         break
  490.                     else:
  491.                         # Shortcut.  Avoid data copy through buf when returning
  492.                         # a substring of our first recv().
  493.                         return data[:nl]
  494.                 n = len(data)
  495.                 if n == size and not buf_len:
  496.                     # Shortcut.  Avoid data copy through buf when
  497.                     # returning exactly all of our first recv().
  498.                     return data
  499.                 if n >= left:
  500.                     buf.write(data[:left])
  501.                     self._rbuf.write(data[left:])
  502.                     break
  503.                 buf.write(data)
  504.                 buf_len += n
  505.                 #assert buf_len == buf.tell()
  506.             return buf.getvalue()
  507.  
  508.     def readlines(self, sizehint=0):
  509.         total = 0
  510.         list = []
  511.         while True:
  512.             line = self.readline()
  513.             if not line:
  514.                 break
  515.             list.append(line)
  516.             total += len(line)
  517.             if sizehint and total >= sizehint:
  518.                 break
  519.         return list
  520.  
  521.     # Iterator protocols
  522.  
  523.     def __iter__(self):
  524.         return self
  525.  
  526.     def next(self):
  527.         line = self.readline()
  528.         if not line:
  529.             raise StopIteration
  530.         return line
  531.  
  532. _GLOBAL_DEFAULT_TIMEOUT = object()
  533.  
  534. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
  535.     """Connect to *address* and return the socket object.
  536.  
  537.     Convenience function.  Connect to *address* (a 2-tuple ``(host,
  538.     port)``) and return the socket object.  Passing the optional
  539.     *timeout* parameter will set the timeout on the socket instance
  540.     before attempting to connect.  If no *timeout* is supplied, the
  541.     global default timeout setting returned by :func:`getdefaulttimeout`
  542.     is used.
  543.     """
  544.  
  545.     msg = "getaddrinfo returns an empty list"
  546.     host, port = address
  547.     for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  548.         af, socktype, proto, canonname, sa = res
  549.         sock = None
  550.         try:
  551.             sock = socket(af, socktype, proto)
  552.             if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  553.                 sock.settimeout(timeout)
  554.             sock.connect(sa)
  555.             return sock
  556.  
  557.         except error, msg:
  558.             if sock is not None:
  559.                 sock.close()
  560.  
  561.     raise error, msg
  562.